<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <todo-header @addName="addName"  />
    <!-- 主体部分 -->
    <todo-main :list="showList" @shan="delTask" @changeDone="hChangeDone" @changeAll="changeAll" />
    <!-- 底部部分 -->
    <todo-footer
      :list="showList"
      @clearDone="clearDone"
      @changeType="hChangeType"
    />
  </section>
</template>

<script>
import TodoFooter from "./components/TodoFooter.vue";
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
export default {
  components: { TodoHeader, TodoFooter, TodoMain },
  data() {
    return {
      list:JSON.parse(localStorage.getItem('list'))||[],
      type: 'all',
    };
  },
  methods: {
    delTask(id) {
      const index = this.list.findIndex((item) => item.id === id);
      this.list.splice(index, 1);
    },
    hChangeDone(id) {
      //父组件找到对应的元素将isDone取反
      const obj = this.list.find((item) => item.id === id);
      obj.isDone = !obj.isDone;
    },
    addName(name) {
      this.list.push({
        id: Date.now(),
        name,
        isDone: false,
      });
    },
    clearDone() {
      //进行筛选，isDone为false筛选出来，显示页面中
      this.list = this.list.filter((item) => !item.isDone);
    },
    hChangeType(type) {
      this.type = type;
    },
    changeAll(val){
      this.list.forEach(item=>item.isDone=val)
    }
  },
  computed: {
    showList() {
      if(this.type==='all'){
        return this.list
      }else if(this.type==='active'){
        return this.list.filter(item=>!item.isDone)
      }else if(this.type  ==='completed'){
        return this.list.filter(item=>item.isDone)
      }
    },
  },
  watch:{
    list:{
      deep:true,
      handler(){
        localStorage.setItem('list',JSON.stringify(this.list))
      }
    }
  }
};
</script>

<style></style>
